package com.local.cart.service.impl;

import com.local.cart.mapper.ShoppingCartMapper;
import com.local.cart.pojo.ShoppingCart;
import com.local.cart.service.ShoppingCartService;
import com.local.common.constants.BusinessException;
import com.local.common.constants.CommonConstants;
import com.local.common.constants.ExceptionCodeEnum;
import com.local.common.util.ResultUtil;
import com.local.goods.feign.GoodsServiceFeign;
import com.local.goods.pojo.Goods;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;


@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private GoodsServiceFeign goodsServiceFeign;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 加入购物车
     * @param shoppingCart
     * @return
     */
    @Override
    public Integer addToShoppingCart(ShoppingCart shoppingCart) {
        Integer userId = shoppingCart.getUserId();
        Integer goodsId = shoppingCart.getGoodsId();
        Integer goodsCount = shoppingCart.getGoodsCount();

        ResultUtil<Goods> goodsResult = goodsServiceFeign.getSimpleById(shoppingCart.getGoodsId());
        if (goodsResult.getCode() != 200) {
            throw new BusinessException(goodsResult.getCode(), goodsResult.getMessage());
        }
        Goods goods = goodsResult.getData();
        if (Objects.isNull(goods)) {
            //商品不存在
            throw new BusinessException(
                    ExceptionCodeEnum.GOODS_NOT_EXIST.getCode(),
                    ExceptionCodeEnum.GOODS_NOT_EXIST.getMessage()
            );
        } else if (goods.getGoodsSellStatus() == 1) {
            //商品已下架
            throw new BusinessException(
                    ExceptionCodeEnum.GOODS_PUT_DOWN.getCode(),
                    ExceptionCodeEnum.GOODS_PUT_DOWN.getMessage()
            );
        }

        ShoppingCart shoppingCartDB = shoppingCartMapper.getByUserIdGoodsId(userId, goodsId);
        Integer userGoodsCount = shoppingCartMapper.getCountByUserId(userId);
        userGoodsCount = Objects.isNull(userGoodsCount) ? 0 : userGoodsCount;

        if (goodsCount > CommonConstants.SHOPPING_CART_ITEM_LIMIT_NUMBER ||
                (!Objects.isNull(shoppingCartDB) && goodsCount + shoppingCartDB.getGoodsCount() > CommonConstants.SHOPPING_CART_ITEM_LIMIT_NUMBER)) {
            //购物车中单个商品的最大购买数量(可根据自身需求修改)
            throw new BusinessException(
                    ExceptionCodeEnum.GOODS_COUNT_CART_ITEM_LIMIT.getCode(),
                    ExceptionCodeEnum.GOODS_COUNT_CART_ITEM_LIMIT.getMessage()
            );
        }
        if (goodsCount > CommonConstants.SHOPPING_CART_ITEM_TOTAL_NUMBER || goodsCount + userGoodsCount > CommonConstants.SHOPPING_CART_ITEM_TOTAL_NUMBER) {
            //购物车中商品的最大数量(可根据自身需求修改)
            throw new BusinessException(
                    ExceptionCodeEnum.GOODS_COUNT_CART_LIMIT.getCode(),
                    ExceptionCodeEnum.GOODS_COUNT_CART_LIMIT.getMessage()
            );
        }

        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        if (Objects.isNull(shoppingCartDB)) {
            //如果购物车不存在该商品，则新增
            shoppingCart.setIsDeleted(0);
            shoppingCart.setCreateTime(dateTime);
            shoppingCart.setUpdateTime(dateTime);
            shoppingCart.setGoodsCoverImg(goods.getGoodsCoverImg());
            shoppingCart.setGoodsName(goods.getGoodsName().length() > 30 ? goods.getGoodsName().substring(0,30) + "..." : goods.getGoodsName());
            shoppingCart.setSellingPrice(goods.getSellingPrice());
            return shoppingCartMapper.save(shoppingCart);

        } else {
            BeanUtils.copyProperties(shoppingCartDB, shoppingCart);
            shoppingCart.setGoodsCount(shoppingCart.getGoodsCount() + goodsCount);
            shoppingCart.setUpdateTime(dateTime);
            //如果购物车已存在该商品，则更新商品数
            return shoppingCartMapper.updateGoodsCount(shoppingCart);
        }
    }


//    /**
//     * 将用户购物车数据复制到session。在用户登录时执行本操作
//     * @param session
//     * @return
//     */
//    @Override
//    public Integer addShoppingCartToSession(HttpSession session) {
//        if (Objects.isNull(session.getAttribute(Constants.MALL_USER_SESSION_KEY))) {
//            return -1; //请先登录
//        }
//
//        User user = (User) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
//        List<ShoppingCart> shoppingCartItemList = shoppingCartMapper.getByUserId(user.getUserId());
//        if (Objects.isNull(shoppingCartItemList) || shoppingCartItemList.isEmpty()) {
//            session.setAttribute(Constants.USER_SHOPPING_CART_ITEM_LIST, shoppingCartItemList);
//            return 0; //购物车为空，无需操作
//        }
//        //取出所有的 goodsId
//        List<Integer> goodsIds = shoppingCartItemList.stream().map(ShoppingCart::getGoodsId).collect(Collectors.toList());
//        List<Goods> goodsList = goodsMapper.getGoodsListByIds(goodsIds);
//        for (ShoppingCart shoppingCart : shoppingCartItemList) {
//            for (Goods goods : goodsList) {
//                if (shoppingCart.getGoodsId().equals(goods.getGoodsId())) {
//                    shoppingCart.setGoodsCoverImg(goods.getGoodsCoverImg());
//                    shoppingCart.setGoodsName(goods.getGoodsName().length() > 30 ? goods.getGoodsName().substring(0, 30) + "..." : goods.getGoodsName());
//                    shoppingCart.setSellingPrice(goods.getSellingPrice());
//                }
//            }
//        }
//        session.setAttribute(Constants.USER_SHOPPING_CART_ITEM_LIST, shoppingCartItemList);
//
//        return null;
//    }

    /**
     * 加入购物车时，将数据也更新到session
     * @param session
     * @param shoppingCart
     * @return
     */
//    @Override
//    public Integer addGoodsToShoppingCartSession(HttpSession session, ShoppingCart shoppingCart) {
//        List<ShoppingCart> shoppingCartList = new ArrayList<>();
//        if (Objects.nonNull(session.getAttribute(CommonConstants.USER_SHOPPING_CART_ITEM_LIST))) {
//            shoppingCartList = (List<ShoppingCart>) session.getAttribute(CommonConstants.USER_SHOPPING_CART_ITEM_LIST);
//        }
//
//        if (shoppingCartList.isEmpty()) {
//            //session中没有购物车，则直接新增该条购物车数据
//            shoppingCartList.add(0, shoppingCart);
//        } else {
//            Boolean flag = false;
//            for (ShoppingCart cart : shoppingCartList) {
//                //session中有该购物车数据，则更新该数据的购买数量
//                if (cart.getGoodsId().equals(shoppingCart.getGoodsId())) {
//                    flag = true;
//                    cart.setGoodsCount(shoppingCart.getGoodsCount());
//                    break;
//                }
//            }
//
//            //session中没有购物车数据，则直接新增
//            if (!flag) {
//                shoppingCartList.add(0, shoppingCart);
//            }
//        }
//
//        //将数据更新到session
//        session.removeAttribute(Constants.USER_SHOPPING_CART_ITEM_LIST);
//        session.setAttribute(Constants.USER_SHOPPING_CART_ITEM_LIST, shoppingCartList);
//
//        return null;
//    }


    /**
     * 清空session中该用户的购物车数据。用于用户付款时，以及退出登录时
     * @param session
     * @return
     */
//    @Override
//    public Integer cleanShoppingCartSession(HttpSession session) {
//        //清除用户购物车的session
//        session.removeAttribute(Constants.USER_SHOPPING_CART_ITEM_LIST);
//        return null;
//    }


    /**
     * 删除
     * @param cartItemId
     * @return
     */
    @Override
    public Integer deleteByCartItemId(Integer cartItemId) {
        return shoppingCartMapper.deleteByCartItemId(cartItemId);
    }


    /**
     * 删除session中的记录
     * @param cartItemId
     * @param session
     * @return
     */
//    @Override
//    public void deleteSessionByCartItemId(HttpSession session, Integer cartItemId) {
//        Object attribute = session.getAttribute(Constants.USER_SHOPPING_CART_ITEM_LIST);
//        if (Objects.nonNull(attribute)) {
//            List<ShoppingCart> shoppingCartList = (List<ShoppingCart>) attribute;
//            Iterator<ShoppingCart> iterator = shoppingCartList.iterator();
//            while (iterator.hasNext()) {
//                ShoppingCart shoppingCart = iterator.next();
//                if (shoppingCart.getCartItemId().equals(cartItemId)) {
//                    iterator.remove();
//                }
//            }
//            session.removeAttribute(Constants.USER_SHOPPING_CART_ITEM_LIST);
//            session.setAttribute(Constants.USER_SHOPPING_CART_ITEM_LIST, shoppingCartList);
//        }
//    }


    /**
     * 更新商品数量
     * @param shoppingCart
     * @return
     */
    @Override
    public Integer updateGoodsCount(ShoppingCart shoppingCart) {
        Integer goodsCount = shoppingCart.getGoodsCount();

        ResultUtil<Goods> goodsResult = goodsServiceFeign.getSimpleById(shoppingCart.getGoodsId());
        if (goodsResult.getCode() != 200) {
            throw new BusinessException(goodsResult.getCode(), goodsResult.getMessage());
        }
        Goods goods = goodsResult.getData();

        if (Objects.isNull(goods)) {
            //商品不存在
            throw new BusinessException(
                    ExceptionCodeEnum.GOODS_NOT_EXIST.getCode(),
                    ExceptionCodeEnum.GOODS_NOT_EXIST.getMessage()
            );
        } else if (goods.getGoodsSellStatus() == 1) {
            //商品已下架
            throw new BusinessException(
                    ExceptionCodeEnum.GOODS_PUT_DOWN.getCode(),
                    ExceptionCodeEnum.GOODS_PUT_DOWN.getMessage()
            );
        }

        if (goodsCount > CommonConstants.SHOPPING_CART_ITEM_LIMIT_NUMBER) {
            //购物车中单个商品的最大购买数量(可根据自身需求修改)
            throw new BusinessException(
                    ExceptionCodeEnum.GOODS_COUNT_CART_ITEM_LIMIT.getCode(),
                    ExceptionCodeEnum.GOODS_COUNT_CART_ITEM_LIMIT.getMessage()
            );
        }

        Integer goodsCountTotal = 0;
        //查询用户的所有购物车列表
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getByUserId(shoppingCart.getUserId());
        for (ShoppingCart cart : shoppingCartList) {
            if (cart.getCartItemId() != shoppingCart.getCartItemId()) {
                goodsCountTotal += cart.getGoodsCount();
            }
        }
        //购物车中商品的最大数量(可根据自身需求修改)
        if (goodsCount > CommonConstants.SHOPPING_CART_ITEM_TOTAL_NUMBER || goodsCount + goodsCountTotal > CommonConstants.SHOPPING_CART_ITEM_TOTAL_NUMBER) {
            throw new BusinessException(
                    ExceptionCodeEnum.GOODS_COUNT_CART_LIMIT.getCode(),
                    ExceptionCodeEnum.GOODS_COUNT_CART_LIMIT.getMessage()
            );
        }

        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        shoppingCart.setGoodsCount(goodsCount);
        shoppingCart.setUpdateTime(dateTime);

        //如果购物车已存在该商品，则更新商品数
        return shoppingCartMapper.updateGoodsCount(shoppingCart);
    }

    /**
     * 查询某用户的购物车列表
     * @param userId
     * @return
     */
    @Override
    public List<ShoppingCart> getListByUserId(Integer userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getByUserId(userId);
        if (shoppingCartList.size() > 0) {
            Goods goods = null;
            for (ShoppingCart shoppingCart : shoppingCartList) {
                ResultUtil<Goods> goodsResult = goodsServiceFeign.getSimpleById(shoppingCart.getGoodsId());
                if (goodsResult.getCode() != 200) {
                    throw new BusinessException(goodsResult.getCode(), goodsResult.getMessage());
                }
                goods = goodsResult.getData();

                shoppingCart.setGoodsCoverImg(goods.getGoodsCoverImg());
                shoppingCart.setGoodsName(goods.getGoodsName().length() > 30 ? goods.getGoodsName().substring(0,30) + "..." : goods.getGoodsName());
                shoppingCart.setSellingPrice(goods.getSellingPrice());
            }
        }

        return shoppingCartList;
    }


    /**
     * 通过ids批量删除
     * @param ids
     * @return
     */
    @Override
    public Integer deleteByIds(List<Integer> ids) {
        return shoppingCartMapper.deleteByIds(ids);
    }


}
